<?php
namespace app\api\middleware;

/**
 * 中间件处理登录 
 */
class Auth{
	public $userId = 0;
	public $username = '';

	public function handle($request,\Closure $next){
		if(!$this->isLogin()){
			return show(config('status.not_login'),'未登录');
		}
		$request->userId = $this->userId;
		
		$response = $next($request);
		//halt($response);
		return $response;
	}

	/**
	 * 判断是否登录
	 */
	public function isLogin(){
		$accessToken = request()->header('access_token');

		if(empty($accessToken)){
			return false;
		}else{
			$userInfo = cache(config('redis.token_pre').$accessToken);
			//halt($userInfo);
			if(empty($userInfo)){
				return false;
			}
			if(!empty($userInfo['id']) && !empty($userInfo['username'])){
				$this->username = $userInfo['username'];
				$this->userId = $userInfo['id'];
				return true;
			}
		}
	}
}